package services

import (
	"errors"
	"time"

	"backend-api/internal/models"
	"backend-api/pkg/database"
	"backend-api/pkg/utils"

	"gorm.io/gorm"
)

// UserService 用户服务
type UserService struct {
	db *gorm.DB
}

// NewUserService 创建用户服务实例
func NewUserService() *UserService {
	return &UserService{
		db: database.GetDB(),
	}
}

// RegisterRequest 用户注册请求
type RegisterRequest struct {
	Username string `json:"username" binding:"required,min=3,max=50"`
	Email    string `json:"email" binding:"required,email"`
	Password string `json:"password" binding:"required,min=6"`
	Nickname string `json:"nickname"`
	Phone    string `json:"phone"`
}

// LoginRequest 用户登录请求
type LoginRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

// UpdateProfileRequest 更新用户信息请求
type UpdateProfileRequest struct {
	Nickname string     `json:"nickname"`
	Avatar   string     `json:"avatar"`
	Phone    string     `json:"phone"`
	Gender   int        `json:"gender"`
	Birthday *time.Time `json:"birthday"`
}

// LoginResponse 登录响应
type LoginResponse struct {
	Token string                `json:"token"`
	User  *models.UserResponse `json:"user"`
}

// Register 用户注册
func (s *UserService) Register(req *RegisterRequest) (*models.UserResponse, error) {
	// 检查用户名是否已存在
	var existingUser models.User
	if err := s.db.Where("username = ?", req.Username).First(&existingUser).Error; err == nil {
		return nil, errors.New("用户名已存在")
	}

	// 检查邮箱是否已存在
	if err := s.db.Where("email = ?", req.Email).First(&existingUser).Error; err == nil {
		return nil, errors.New("邮箱已存在")
	}

	// 加密密码
	hashedPassword, err := utils.HashPassword(req.Password)
	if err != nil {
		return nil, errors.New("密码加密失败")
	}

	// 创建用户
	user := models.User{
		Username: req.Username,
		Email:    req.Email,
		Password: hashedPassword,
		Nickname: req.Nickname,
		Phone:    req.Phone,
		Status:   1, // 默认启用
	}

	if err := s.db.Create(&user).Error; err != nil {
		return nil, errors.New("创建用户失败")
	}

	return user.ToResponse(), nil
}

// Login 用户登录
func (s *UserService) Login(req *LoginRequest) (*LoginResponse, error) {
	// 查找用户
	var user models.User
	if err := s.db.Where("username = ? OR email = ?", req.Username, req.Username).First(&user).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("用户不存在")
		}
		return nil, errors.New("查询用户失败")
	}

	// 检查用户状态
	if user.Status == 0 {
		return nil, errors.New("用户已被禁用")
	}

	// 验证密码
	if !utils.CheckPassword(req.Password, user.Password) {
		return nil, errors.New("密码错误")
	}

	// 生成JWT令牌
	token, err := utils.GenerateFrontendToken(user.ID, user.UUID, user.Username)
	if err != nil {
		return nil, errors.New("生成令牌失败")
	}

	// 更新最后登录时间
	now := time.Now()
	user.LastLogin = &now
	s.db.Save(&user)

	return &LoginResponse{
		Token: token,
		User:  user.ToResponse(),
	}, nil
}

// GetProfile 获取用户信息
func (s *UserService) GetProfile(userID uint) (*models.UserResponse, error) {
	var user models.User
	if err := s.db.First(&user, userID).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("用户不存在")
		}
		return nil, errors.New("查询用户失败")
	}

	return user.ToResponse(), nil
}

// UpdateProfile 更新用户信息
func (s *UserService) UpdateProfile(userID uint, req *UpdateProfileRequest) (*models.UserResponse, error) {
	var user models.User
	if err := s.db.First(&user, userID).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("用户不存在")
		}
		return nil, errors.New("查询用户失败")
	}

	// 更新用户信息
	if req.Nickname != "" {
		user.Nickname = req.Nickname
	}
	if req.Avatar != "" {
		user.Avatar = req.Avatar
	}
	if req.Phone != "" {
		user.Phone = req.Phone
	}
	if req.Gender >= 0 && req.Gender <= 2 {
		user.Gender = req.Gender
	}
	if req.Birthday != nil {
		user.Birthday = req.Birthday
	}

	if err := s.db.Save(&user).Error; err != nil {
		return nil, errors.New("更新用户信息失败")
	}

	return user.ToResponse(), nil
}

// GetUserByUUID 根据UUID获取用户
func (s *UserService) GetUserByUUID(uuid string) (*models.UserResponse, error) {
	var user models.User
	if err := s.db.Where("uuid = ?", uuid).First(&user).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("用户不存在")
		}
		return nil, errors.New("查询用户失败")
	}

	return user.ToResponse(), nil
}